package com.cloudfast.oauth.endpoint;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudfast.common.result.ApiResponse;
import com.cloudfast.context.error.CloudException;
import com.cloudfast.context.error.ErrorCode;

/**
 * 控制层异常类
 *
 * @author liuyw
 */
@ControllerAdvice
public class CloudExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    /**
     * 框架异常处理类
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(CloudException.class)
    public ApiResponse handle(CloudException e, HttpServletResponse response) throws IOException, ServletException {
        ApiResponse apiResult = null;
        logger.error("当前异常:{}", e.getException().getMessage());
        if (e.getException() instanceof NoSuchClientException) {
            apiResult = ApiResponse.message(ErrorCode.CLIENT_ERROR);
        } else if (e.getException() instanceof InvalidGrantException) {
            apiResult = ApiResponse.message(ErrorCode.USERNAME_PASSWORD_ERROR);
        } else if (e.getException() instanceof UnsupportedGrantTypeException) {
            apiResult = ApiResponse.message(ErrorCode.GRANT_TYPE_ERROR);
        } else if (e.getException() instanceof CloudException) {
            CloudException cloudException = (CloudException) e.getException();
            if (cloudException.getCode() == ErrorCode.RE_LOGIN.getCode()) {
                apiResult = ApiResponse.message(ErrorCode.RE_LOGIN);
            } else if (cloudException.getCode() == ErrorCode.AUTHORIZATION_ERROR.getCode()) {
                apiResult = ApiResponse.message(ErrorCode.AUTHORIZATION_ERROR);
            } else if (e.getErrorCode() != null) {
                apiResult = ApiResponse.message(e.getErrorCode());
            } else if (cloudException.getErrorCode() != null) {
                apiResult = ApiResponse.message(cloudException.getErrorCode());
            } else {
                apiResult = ApiResponse.message(ErrorCode.SYSTEM_ERROR);
            }

        } else {
            apiResult = ApiResponse.message(ErrorCode.USERNAME_PASSWORD_ERROR);
        }

        return apiResult;

    }
}